import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';

import { login, userInfo } from '@/services/index';
import { getToken, setToken, removeToken } from '@/utils/index';
import { LoginUser } from '@/utils/interface'

export interface LoginModelState {
    isLogin: boolean;
    loginuser: LoginUser
}

export interface LoginModelType {
    namespace: 'login';
    state: LoginModelState;
    effects: {
        login: Effect;
        logout: Effect;
        userInfo: Effect;

    };
    reducers: {
        save: Reducer<LoginModelState>;
    }
    subscriptions: { setup: Subscription };
}

const UserModel: LoginModelType = {
    namespace: 'login',

    state: {
        isLogin: !!getToken(),
        loginuser: {
            avatar: "",
            iat: 0,
            identity_id: "",
            identity_text: "",
            signTime: 0,
            user_id: "",
            user_name: "",
        }
    },
    effects: {
        *login({ payload }, { call, put }) {
            let result = yield call(login, payload);
            if (result.code === 1) {
                yield put({
                    type: 'save',
                    payload: { isLogin: true }
                })
                setToken(result.token, payload.remember);
            }
        },
        *logout({ }, { put }) {
            removeToken();
            yield put({
                type: 'save',
                payload: { isLogin: false }
            })
        },
        *userInfo({ payload }, { call, put }) {
            let result = yield call(userInfo);
            if (result.code === 1) {
                yield put({
                    type: 'save',
                    payload: { loginuser: result.data }
                })

            }
        },
    },
    reducers: {
        save(state, action) {
            return {
                ...state,
                ...action.payload,
            }
        }
    },
    subscriptions: {
        setup({ dispatch, history }) {
            return history.listen(({ pathname }) => {
                if (!getToken()) {
                    history.replace(`/login?from=${encodeURIComponent(pathname)}`);
                } else {
                    if (pathname == '/login') {
                        history.goBack();
                    }
                }
                if (pathname === '/') {
                    history.replace('/main/');
                }
            });
        }
    }
};

export default UserModel;